<template>
  <el-container class="GoodsList">
    <el-header class="mt20 flex">
      <span class="title fs18 mr10">我的商品列表</span>
      <Cbutton size="small" icon="el-icon-plus" @click.native="toModifyGoods('add')">发布商品</Cbutton>
      <el-divider />
    </el-header>
    <el-main>
      <div class="flex mb15">
        <span class="title fs16 mr5" style="align-self: end;">筛选：</span>
        <Cinput v-model="search.value" icon="search" placeholder="请输入关键词" style="width: 500px;max-width: 100%;" @input="searchGoods">搜索商品</Cinput>
      </div>
      <el-skeleton :loading="loading" animated :throttle="500">
        <template #template>
          <el-skeleton-item variant="h1" />
          <el-skeleton-item variant="h1" class="mt10" />
        </template>
        <el-radio-group v-model="categoryOneId" size="medium" class="flex" @change="getCategoryTwo">
          <el-radio-button v-for="(item, index) in categoryOneList" :key="index" :label="item.id" style="letter-spacing: 2px;">
            {{ item.name }}
          </el-radio-button>
        </el-radio-group>
        <!-- 当选择了一级后才展示 -->
        <div v-if="categoryOneId">
          <el-radio-group v-if="categoryTwoList.length > 0" v-model="categoryTwoId" size="small" class="flex mt10" @change="getList">
            <el-radio-button v-for="(item, index) in categoryTwoList" :key="index" :label="item.id" style="letter-spacing: 2px;">
              <Cimage :src="item.icon[0].url" width="30px" height="30px" fit="cover" />
              <span class="ml5">{{ item.name }}</span>
            </el-radio-button>
          </el-radio-group>
          <el-tag v-else type="danger" class="mt10" :disable-transitions="true">未有数据</el-tag>
        </div>
      </el-skeleton>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        class="mt20"
        style="width: 100%"
        border
      >
        <el-table-column prop="createTime" label="上架时间" show-overflow-tooltip align="center" min-width="10%">
          <template slot-scope="{row}">
            <span>{{ row.createTime | setTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="iconId" label="商品封面" align="center" min-width="10%">
          <template slot-scope="{row}">
            <Cimage :src="row.iconId[0].url" fit="cover" style="cursor: pointer;border-radius: 5px;" width="60px" height="60px" @click.native="openViewr(row.iconId[0].url)" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" show-overflow-tooltip align="center" min-width="14%">
          <template slot-scope="{row}">
            <span>{{ row.name | isNullData }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="hot" label="商品标签" align="center" min-width="12%">
          <template slot-scope="{row}">
            <el-tag>{{ row.hot | isNullData }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="商品类别" align="center" min-width="10%">
          <template slot-scope="{row}">
            <el-tag type="warning">{{ row.typeName | isNullData }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" align="center" min-width="12%">
          <template slot-scope="{row}">
            <div>原价: <span style="text-decoration:line-through;">￥{{ row.oldPrice }}</span></div>
            <div>现价: <span style="color:#F56C6C;">￥{{ row.price }}</span></div>
          </template>
        </el-table-column>
        <el-table-column prop="stock_num" label="商品库存" align="center" min-width="10%">
          <template slot-scope="{row}">
            <el-tag type="info">{{ row.stock_num | isNullData }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="22%">
          <template slot-scope="{row}">
            <el-button type="info" icon="el-icon-search" size="small" @click="toDetailsGoods(row.id)">查看</el-button>
            <el-button type="primary" icon="el-icon-edit" size="small" @click="toModifyGoods('modify', row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Cpagination
        :total="listQuery.total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.size"
        position="fixed"
        @pagination="getList"
      />
    </el-main>
    <CImageViewer :viewer-image-url.sync="viewr.viewerImageUrl" :visible.sync="viewr.visible" />
  </el-container>
</template>
<script>
import {
  myGoodsList
} from '@/api/myGoods'
import {
  categoryGetOne,
  categoryGetTwo
} from '@/api/category'
export default {
  data() {
    return {
      loading: true,
      tableLoading: true,
      search: {
        value: '', // 搜索关键词
        timer: '' // 定时器
      },
      categoryOneList: [], // 一级分类数据
      categoryOneId: '', // 一级分类id

      categoryTwoList: [], // 二级分类数据
      categoryTwoId: '', // 二级分类id
      tableData: [], // 商品数据
      listQuery: {
        page: 1,
        size: 10,
        total: 0
      },
      viewr: { // 图片预览数据
        visible: false,
        viewerImageUrl: []
      }
    }
  },
  created() {
    this.getCategoryOne()
    this.getList()
  },
  methods: {
    // 跳转商品详情
    toDetailsGoods(id) {
      this.$router.push({
        name: 'GoodsDetails',
        path: '/goods/details',
        query: { id: id }
      })
    },
    // 跳转发布商品
    toModifyGoods(type, id) {
      let data = {}
      switch (type) {
        case 'add':
          data = {
            name: 'GoodsAdd',
            path: '/goods/add',
            query: { type: type }
          }
          break
        case 'modify':
          data = {
            name: 'GoodsModify',
            path: '/goods/modify',
            query: {
              type: type,
              id: id
            }
          }
          break
      }
      this.$router.push(data)
    },
    // 搜索商品输入框回调
    searchGoods() {
      // 简单防抖 500ms
      if (this.search.timer) clearTimeout(this.search.timer)
      this.search.timer = setTimeout(() => {
        this.listQuery = { // 搜索前初始化分页
          page: 1,
          size: 10,
          total: 0
        }
        this.getList()
      }, 500)
    },
    // 打开预览大图组件
    openViewr(url) {
      this.viewr.viewerImageUrl = [url]
      this.viewr.visible = true
    },
    // 初始化获取一级分类
    async getCategoryOne() {
      const res = await categoryGetOne()
      if (res.code === 0) {
        const { data } = res
        this.categoryOneList = data
        this.loading = false
      }
    },
    // 获取二级分类数据
    async getCategoryTwo() {
      const res = await categoryGetTwo({
        parentId: this.categoryOneId
      })
      if (res.code === 0) {
        const { data } = res
        this.categoryTwoList = data
      }
    },
    // 获取商品列表数据
    async getList() {
      const res = await myGoodsList({
        page: this.listQuery.page,
        size: this.listQuery.size,
        categoryTwoId: this.categoryTwoId,
        value: this.search.value
      })
      if (res.code === 0) {
        const { data } = res
        const value = await this.filterCategory(data.list)
        if (value) {
          this.tableData = data.list
          this.listQuery.total = data.total
          this.tableLoading = false
        }
      }
    },
    // 商品分类匹配
    filterCategory(list) {
      return new Promise(resolve => {
        if (list.length === 0) {
          resolve(list)
          return
        }
        categoryGetTwo().then(res => { // 直接获取全部二级分类
          if (res.code === 0) {
            const { data } = res
            list.forEach(item => {
              const index = data.findIndex(v => item.parentId === v.id)
              item['typeName'] = data[index].name || '未命名分类'
            })
            resolve(list)
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-radio-button__inner{
  display: flex;
  align-items: center;
}
.GoodsList{
  margin-bottom: 20px;
}
</style>
